import numpy as np
import pandas as pd
import scipy
import sklearn
from sklearn.pipeline import make_pipeline
import os

# skimage
import skimage
import skimage.color
import skimage.transform
import skimage.feature
import skimage.io
from sklearn.base import BaseEstimator, TransformerMixin
import matplotlib.pyplot as plt
import pickle

# load the model
model = pickle.load(open('./pickle_files/dsa_image_classification_sgd.pickle','rb'))
scaler = pickle.load(open('./pickle_files/dsa_scaler.pickle','rb'))

def pipeline_model(path,scaler_transform,model_sgd):
    # pipeline model
    image = skimage.io.imread(path)
    # transform image into 80 x 80
    image_resize = skimage.transform.resize(image,(80,80))
    image_scale = 255*image_resize
    image_transform = image_scale.astype(np.uint8)
    # rgb to gray
    gray = skimage.color.rgb2gray(image_transform)
    # hog feature. Notice, hyper-parameters below should be exactly same as we set before for best model.
    feature_vector = skimage.feature.hog(gray,
                                  orientations=8,
                                  pixels_per_cell=(8,8),cells_per_block=(3,3))
    # scaling
    
    scalex = scaler_transform.transform(feature_vector.reshape(1,-1))
    result = model_sgd.predict(scalex)
    # decision function # confidence
    decision_value = model_sgd.decision_function(scalex).flatten()
    labels = model_sgd.classes_
    # probability
    z = scipy.stats.zscore(decision_value)
    prob_value = scipy.special.softmax(z)
    
    # top 5
    top_5_prob_ind = prob_value.argsort()[::-1][:5]
    top_labels = labels[top_5_prob_ind]
    top_prob = prob_value[top_5_prob_ind]
    # put in dictornary
    top_dict = dict()
    for key,val in zip(top_labels,top_prob):
        top_dict.update({key:np.round(val,3)})
    
    return top_dict

res = pipeline_model('./Images/eagle.jpg',scaler,model)
print("prediction result: ", res)
